package com.yqyd.web.controller.nbot.app;


import com.google.common.collect.ImmutableMap;
import com.yqyd.common.annotation.Anonymous;
import com.yqyd.common.core.domain.R;
import com.yqyd.common.core.domain.entity.SysUser;
import com.yqyd.common.utils.SecurityUtils;
import com.yqyd.common.utils.WechatUtils;
import com.yqyd.framework.web.service.SysLoginService;
import com.yqyd.hy.vo.UserInfoVo;
import com.yqyd.nbot.domain.NbotUserNumber;
import com.yqyd.nbot.service.INbotUserNumberService;
import com.yqyd.system.service.ISysUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Collections;
import java.util.Objects;

@RestController
@RequestMapping("/api/nbot/login")
@CrossOrigin
public class LoginApi {

    private final static String APPID = "wx2d5945a111f3d77e";
    private final static String APP_SECRET = "924529d36db67cbc8e42d4dbb5d43c93";
    private final static String PWD = "nbot8888";
    private final static String PLATFROM = "NBOT";
    // 未授权状态
    private final static Integer NONE_AUTH_STATUS = 0;

    @Resource
    private ISysUserService sysUserService;

    @Resource
    private SysLoginService loginService;

    @Resource
    private INbotUserNumberService nbotUserNumberService;

    @GetMapping("/check")
    @Anonymous
    public R<Boolean> check() {
        return R.ok(SecurityUtils.checkLogin()) ;
    }


    @PostMapping("/Auth")
    @Anonymous
    public R<ImmutableMap<String, Object>> Auth(@RequestParam("code") String code) {
        String openId = WechatUtils.Openid(code,APPID, APP_SECRET);
        if (StringUtils.isEmpty(openId)) {
            return R.fail("微信上授权登录失败：OPENID为空");
        }
        // 登录账号
        String account = PLATFROM + "_" + openId;
        // 查询用户是否存在
        SysUser user = sysUserService.selectEasyUserByOpenId(account);
        if (Objects.isNull(user)) {
            // TODO: 注册用户
            user = new SysUser();
            user.setPlatform(PLATFROM);
            user.setOpenId(openId);
            user.setUserName(account);
            user.setNickName("微信用户");
            user.setPassword(SecurityUtils.encryptPassword(PWD));
            user.setAuthStatus(NONE_AUTH_STATUS);
            sysUserService.insertUser(user);
            // TODO: 注册用户后，给用户发送注册成功的消息
            // TODO: 同时添加用户的统计
            nbotUserNumberService.insertNbotUserNumber(new NbotUserNumber()
               .setUserId(user.getUserId()));
        }
        // TODO: 登录返回TOKEN和认证授权状态
        return R.ok( ImmutableMap.of("auth", user.getAuthStatus(), "token", loginService.login(account, PWD, "", "")));
    }

}
